package com.example.demo.service.impl;

import com.example.demo.client.vm.cssmqry.menu.MenuTreeVm;
import com.example.demo.client.vm.sysbasequery.FullMenuIdsVm;
import com.ffcs.oss.common.utils.tree.TreeBuilder;
import com.example.demo.domain.Menu;
import com.example.demo.enums.EnabledEnum;
import com.example.demo.mapper.HelpMapper;
import com.example.demo.mapper.MenuMapper;
import com.example.demo.repository.MenuRepository;
import com.example.demo.security.SecurityUtils;
import com.example.demo.service.BaseService;
import com.example.demo.service.MenuService;
import com.example.demo.web.rest.constant.DatabaseConstant;
import com.example.demo.web.rest.evt.*;
import com.example.demo.web.rest.util.SsoUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author zhengmf
 * @Date 2018/12/29  9:49
 */
@Service
@Transactional
public class MenuServiceImpl extends BaseService implements MenuService {

    @Autowired
    private MenuRepository menuRepository;
    @Autowired
    private HelpMapper helpMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public Long saveMenu(SaveMenuEvt evt) {
        Menu menu = new Menu();
        if(evt.getParentId() == null){
            evt.setParentId(0L);
        }
        BeanUtils.copyProperties(evt,menu);
        Long parentId = menu.getParentId();
        if(evt.getMenuId() == null){
            TableIdSizeEvt tableIdSizeEvt = new TableIdSizeEvt(DatabaseConstant.TABLE_NAME_MENU,DatabaseConstant.ID_SIZE);
            menu.setMenuId(baseQueryClient.getTableId(tableIdSizeEvt));
        }
        Menu newMenu = menuRepository.save(menu);
        Long menuId = newMenu.getMenuId();
        //如果这个菜单指定了父级菜单
        if(parentId != null && !parentId.equals(0L)){
            IdEvt idEvt = new IdEvt();
            idEvt.setId(parentId);
            String parentFullMenuId  = baseQueryClient.getFullMenuIdById(idEvt).getBody();
            //更新这个菜单的fullmenuId
            menuRepository.updateFullMenuId(parentFullMenuId+menuId+",",menuId);
            //如果更改父级目录，断开子集关系
            if(evt.getChangeParent()) {
                idEvt.setId(menuId);
                //获取所有子级的fullmenuId集合
                List<FullMenuIdsVm> childFullId = baseQueryClient.getChildFullMenuIds(idEvt).getBody();
                if (childFullId != null && childFullId.size() > 0) {
                    for (FullMenuIdsVm vm : childFullId) {
                        //去掉fullmenuid里自己的id
//                        String newFullId = vm.getFullMenuId().replace(menuId.toString() + ",", "");
                        String newFullId = "," + evt.getParentId().toString() + vm.getFullMenuId();
                        //把fullmenuid分割
                        String[] fullIds = newFullId.split(",");
                        //获取倒数第二个id
                        String pid = fullIds[fullIds.length-2];
                        String cid = fullIds[fullIds.length-1];
//                        menuRepository.updateFullMenuIds(newFullId, pid, String.valueOf(vm.getMenuId()));
                        menuMapper.updateFullMenuIds(newFullId, pid, cid);
                    }
                }
            }
        }else {
            menuRepository.updateFullMenuId(","+menuId+",",menuId);
        }
        if(Integer.parseInt(EnabledEnum.DISABLED.getValue()) == evt.getEnabled()){
            menuRepository.DisabledChildren("%," + menuId + ",%");
        }

        //添加帮助目录与菜单的关系
        if(evt.getCatalogIds() !=null && evt.getCatalogIds().size()>0){
            helpMapper.delHelp(evt.getNameEn());
            HelpEvt helpEvt = new HelpEvt();
            helpEvt.setNameEn(evt.getNameEn());
            helpEvt.setCatalogIds(evt.getCatalogIds());
            helpMapper.addHelp(helpEvt);
        }
        return menuId;
    }

    @Override
    public void delMenu(delMenuEvt evt) {
        menuRepository.deleteById(evt.getId());
//        helpMapper.delHelp(evt.getNameEn());
    }

    @Override
    public List<MenuTreeVm> getParentMenuTree(IdEvt evt) {
        List<MenuTreeVm> list = TreeBuilder.newTreeBuilder(MenuTreeVm.class, Long.class)
                .buildToTreeList(menuMapper.getParentMenuTree());
        Long id = evt.getId();
        deleteSelf(list,id);
        return list;
    }

    @Override
    public String ssoLink(String ssoMenuType) throws Exception {
        String ssoLinkUrlParam = "";
        String username = SecurityUtils.getCurrentUserLogin().get();
        logger.info("单点系统为【{}】，当前登录用户为【{}】", ssoMenuType, username);
        switch (ssoMenuType) {
            case "tower":
                ssoLinkUrlParam = "from=fjydzhyy&querycode=" + SsoUtil.getKey(6000, "com.example.demo","fjydzhyy", new String[]{username});
                break;
            default:
                throw new Exception("未知的系统类型【" + ssoMenuType + "】");
        }
        return ssoLinkUrlParam;
    }

    public void deleteSelf(List<MenuTreeVm> list,Long id){
        if(list == null || list.size()==0){
            return;
        }
        for (int i=0;i<list.size();i++) {
            MenuTreeVm vm = list.get(i);
            if (vm.getId().equals(id)) {
                list.remove(i);
                return;
            }
            if (vm.getChildren()!=null && vm.getChildren().size()>0) {
                deleteSelf(vm.getChildren(),id);
            }
        }
    }
}
